<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { formRules, TrainingCategoryOptions, TrainingStatus } from "../utils/types";
import { getTrainingDetail, createTraining, updateTraining } from "@/api/training";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import ArrowLeft from "@iconify-icons/ep/arrow-left";
import Check from "@iconify-icons/ep/check";
import dayjs from "dayjs";

defineOptions({
  name: "TrainingForm"
});

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const formRef = ref();
const isEdit = ref(false);
const trainingId = route.query.id as string;

const formData = ref({
  id: "",
  title: "",
  description: "",
  category: "",
  instructorId: 0,
  instructorName: "",
  maxStudents: 20,
  currentStudents: 0,
  price: 0,
  originalPrice: 0,
  startTime: "",
  endTime: "",
  duration: 0,
  location: "",
  address: "",
  status: TrainingStatus.DRAFT,
  level: 1,
  tags: "",
  coverImage: "",
  content: "",
  requirements: "",
  objectives: "",
  schedule: "",
  materials: "",
  certificate: false,
  remark: ""
});

// 获取培训详情
async function getDetail() {
  if (!trainingId) return;
  
  loading.value = true;
  try {
    // 使用模拟数据
    const mockDetail = {
      id: trainingId,
      title: "羽毛球基础培训",
      description: "这是羽毛球基础培训的详细描述，包含了培训的主要内容和目标。",
      category: "badminton",
      instructorId: 1,
      instructorName: "张教练",
      maxStudents: 25,
      currentStudents: 8,
      price: 150,
      originalPrice: 200,
      startTime: dayjs().add(1, 'week').format('YYYY-MM-DD 09:00:00'),
      endTime: dayjs().add(1, 'week').add(2, 'hour').format('YYYY-MM-DD 11:00:00'),
      duration: 2,
      location: "体育馆A",
      address: "体育中心体育馆A详细地址1号",
      status: TrainingStatus.PUBLISHED,
      level: 1,
      tags: "标签1,培训,运动",
      coverImage: "",
      content: "培训内容详情1，包含理论学习和实践训练。",
      requirements: "报名要求1：身体健康，无运动禁忌。",
      objectives: "培训目标1：掌握基本技能，提升运动水平。",
      schedule: "课程安排1：理论课1小时，实践课1小时。",
      materials: "培训材料1：教学视频，练习手册。",
      certificate: true,
      remark: "备注信息1"
    };
    formData.value = mockDetail;
    
    // 实际开发时使用真实接口
    // const { result } = await getTrainingDetail(trainingId);
    // formData.value = result;
  } catch (error) {
    ElMessage.error("获取培训详情失败");
  } finally {
    loading.value = false;
  }
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    loading.value = true;
    
    if (isEdit.value) {
      // 实际开发时调用更新接口
      // await updateTraining(formData.value);
      ElMessage.success("培训更新成功");
    } else {
      // 实际开发时调用创建接口
      // await createTraining(formData.value);
      ElMessage.success("培训创建成功");
    }
    
    router.push("/training/list");
  } catch (error) {
    ElMessage.error(isEdit.value ? "培训更新失败" : "培训创建失败");
  } finally {
    loading.value = false;
  }
}

// 取消操作
function handleCancel() {
  router.push("/training/list");
}

onMounted(() => {
  if (trainingId) {
    isEdit.value = true;
    getDetail();
  }
});
</script>

<template>
  <div class="main">
    <div class="mb-4">
      <el-button
        :icon="useRenderIcon(ArrowLeft)"
        @click="handleCancel"
      >
        返回列表
      </el-button>
      <el-button
        type="primary"
        :icon="useRenderIcon(Check)"
        :loading="loading"
        @click="handleSubmit"
      >
        {{ isEdit ? '更新培训' : '创建培训' }}
      </el-button>
    </div>

    <el-card v-loading="loading" class="box-card">
      <template #header>
        <div class="card-header">
          <span class="text-lg font-bold">{{ isEdit ? '编辑培训' : '新增培训' }}</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="training-form"
      >
        <el-row :gutter="30">
          <el-col :xs="24" :sm="12">
            <el-form-item label="培训标题" prop="title">
              <el-input
                v-model="formData.title"
                clearable
                placeholder="请输入培训标题"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="培训分类" prop="category">
              <el-select
                v-model="formData.category"
                placeholder="请选择培训分类"
                class="w-full"
              >
                <el-option
                  v-for="item in TrainingCategoryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="讲师姓名" prop="instructorName">
              <el-input
                v-model="formData.instructorName"
                clearable
                placeholder="请输入讲师姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="培训级别" prop="level">
              <el-select
                v-model="formData.level"
                placeholder="请选择培训级别"
                class="w-full"
              >
                <el-option label="初级" :value="1" />
                <el-option label="中级" :value="2" />
                <el-option label="高级" :value="3" />
                <el-option label="专家级" :value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="最大学员数" prop="maxStudents">
              <el-input-number
                v-model="formData.maxStudents"
                :min="1"
                :max="1000"
                placeholder="请输入最大学员数"
                class="w-full"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="培训价格" prop="price">
              <el-input-number
                v-model="formData.price"
                :min="0"
                :precision="2"
                placeholder="请输入培训价格"
                class="w-full"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="原价" prop="originalPrice">
              <el-input-number
                v-model="formData.originalPrice"
                :min="0"
                :precision="2"
                placeholder="请输入原价"
                class="w-full"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="培训时长" prop="duration">
              <el-input-number
                v-model="formData.duration"
                :min="1"
                placeholder="请输入培训时长（小时）"
                class="w-full"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="formData.startTime"
                type="datetime"
                placeholder="请选择开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                class="w-full"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="formData.endTime"
                type="datetime"
                placeholder="请选择结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                class="w-full"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="培训地点" prop="location">
              <el-input
                v-model="formData.location"
                clearable
                placeholder="请输入培训地点"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="详细地址" prop="address">
              <el-input
                v-model="formData.address"
                clearable
                placeholder="请输入详细地址"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="培训状态" prop="status">
              <el-select
                v-model="formData.status"
                placeholder="请选择培训状态"
                class="w-full"
              >
                <el-option label="草稿" :value="0" />
                <el-option label="已发布" :value="1" />
                <el-option label="进行中" :value="2" />
                <el-option label="已完成" :value="3" />
                <el-option label="已取消" :value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="标签" prop="tags">
              <el-input
                v-model="formData.tags"
                clearable
                placeholder="请输入标签，用逗号分隔"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="封面图片" prop="coverImage">
              <el-input
                v-model="formData.coverImage"
                clearable
                placeholder="请输入封面图片URL"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12">
            <el-form-item label="颁发证书">
              <el-switch
                v-model="formData.certificate"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="培训描述" prop="description">
              <el-input
                v-model="formData.description"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                placeholder="请输入培训描述"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="培训内容" prop="content">
              <el-input
                v-model="formData.content"
                :autosize="{ minRows: 3, maxRows: 6 }"
                type="textarea"
                placeholder="请输入培训内容详情"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="报名要求" prop="requirements">
              <el-input
                v-model="formData.requirements"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                placeholder="请输入报名要求"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="培训目标" prop="objectives">
              <el-input
                v-model="formData.objectives"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                placeholder="请输入培训目标"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="课程安排" prop="schedule">
              <el-input
                v-model="formData.schedule"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                placeholder="请输入课程安排"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="培训材料" prop="materials">
              <el-input
                v-model="formData.materials"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                placeholder="请输入培训材料"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formData.remark"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.training-form {
  .el-form-item {
    margin-bottom: 20px;
  }
}
</style>